package com.dy.lock.screen.scoket;

import org.apache.mina.core.filterchain.IoFilterAdapter;
import org.apache.mina.core.session.IoSession;
import org.springframework.util.StringUtils;

import com.dy.lock.screen.constants.TransmissionCode;
import com.dy.lock.screen.utils.CommonUtil;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class TransmissionMessageCheckFilter extends IoFilterAdapter {

	@Override
	public void messageReceived(NextFilter nextFilter, IoSession session,
			Object message) throws Exception {
		Head head = null;
		Gson gson = CommonUtil.gson();
		try {
			try {
				JsonParser parser = new JsonParser();
				JsonObject o = parser.parse(message.toString())
						.getAsJsonObject();
				JsonElement headStr = o.get("head");
				head = gson.fromJson(headStr, Head.class);
				head.setResponseCode(null);
				head.setResponseMessage(null);
			} catch (Exception e) {
				if (head == null)
					head = new Head();
				head.setResponseCode(TransmissionCode.MESSAGE_FORMAT_ERROR
						.getCode());
				head.setResponseMessage(TransmissionCode.MESSAGE_FORMAT_ERROR
						.getMessage());
			}
			if (!StringUtils.hasText(head.getServiceCode())
					|| !StringUtils.hasText(head.getUserId())
					|| !StringUtils.hasText(head.getIp())) {
				head.setResponseCode(TransmissionCode.MESSAGE_HEAD_ERROR
						.getCode());
				head.setResponseMessage(TransmissionCode.MESSAGE_HEAD_ERROR
						.getMessage());
			}
			if (head != null && StringUtils.hasText(head.getResponseCode())) {
				SocketDTO responseSocketDTO = new SocketDTO();
				responseSocketDTO.setHead(head);
				session.write(gson.toJson(responseSocketDTO));
				session.close(true);
				return;
			} else
				nextFilter.messageReceived(session, message);
		} catch (Exception e) {
			if (head == null)
				head = new Head();
			SocketDTO responseSocketDTO = new SocketDTO();
			head.setResponseCode(TransmissionCode.ERROR.getCode());
			head.setResponseMessage(TransmissionCode.ERROR.getMessage());
			responseSocketDTO.setHead(head);
			session.write(gson.toJson(responseSocketDTO));
			session.close(true);
		}
	}
}